package com.cakin;

import org.junit.Test;

import java.sql.*;

/**
 * @ClassName: JdbcTest3
 * @Description: jdbc事务：实现转账
 * @Date: 2020/6/19
 * @Author: cakin
 */
public class JdbcTest3 {
    @Test
    public void test() {
        // useUnicode=true&characterEncoding=utf8 解决中文乱码
        String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf8";
        String username = "root";
        String password = "123456";
        Connection connection = null;

        try {
            // 1 加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            // 2 获得连接对象
            connection = DriverManager.getConnection(url, username, password);
            // 3 开启事务
            connection.setAutoCommit(false);
            // 4 编写SQL
            String sql1 = "update account set money = money-100 where name = 'A'";
            connection.prepareStatement(sql1).executeUpdate();
            // 制造错误
            // int i = 1 / 0;

            String sql2 = "update account set money = money+100 where name = 'B'";
            connection.prepareStatement(sql2).executeUpdate();
            connection.commit();
        } catch (Exception e) {
            try {
                connection.rollback();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            // 6 关闭资源
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
